package com.max.api;


import com.max.common.R;
import com.max.dto.LoginDTO;
import com.max.dto.UserRegisterDTO;
import com.max.service.IUserInfoService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = "用户相关开放接口")
@RestController
@RequestMapping(value = "/open/user")
@Validated
public class UserOpenApi {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public R<?> register(@Valid @RequestBody UserRegisterDTO userRegisterDTO) {
        return R.result(userInfoService.register(userRegisterDTO));
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R<?> login(@Valid @RequestBody LoginDTO dto) {
        UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(loginToken);
        if(authenticate == null){
            return R.error("用户名或密码错误");
        }
        Object principal = authenticate.getPrincipal();
        return R.ok(principal);
    }


}
